package com.hmdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisData;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {


    @Resource
    private StringRedisTemplate stringRedisTemplate;

    //根据id查询商铺
    @Override
    public Result queryShopById(Long id) {

        //第一次优化缓存穿透代码
//        Shop shop = queryWithPassThrough(id);

        //第二次优化代码基于互斥锁的缓存击穿
        Shop shop = queryWithMutex(id);
        if(shop==null)
        {
            return Result.fail("店铺不存在！");
        }

        //第三次优化基于添加逻辑过期时间



        return Result.ok(shop);
    }

    //创建线程池里创建十个线程
    private static final ExecutorService CACHE_REBUILD_EXECUTOR= Executors.newFixedThreadPool(10);


    public Shop queryWithLogicalExpire(Long id) {

        //从Redis中查询商铺缓存
        String key=CACHE_SHOP_KEY+id;
        String shopJson = stringRedisTemplate.opsForValue().get(key);

        //判断是否存在,对与空串，null等都是false
        if(StrUtil.isBlank(shopJson))
        {
            //存在，从Redis中获取并返回
            return null;
        }

        //TODO 命中，需要先把json反序列化为对象

        RedisData redisData = JSONUtil.toBean(shopJson, RedisData.class);

        //得到商铺对象
        JSONObject shopJSON = (JSONObject) redisData.getData();
        Shop shop = JSONUtil.toBean(shopJSON, Shop.class);
        //得到逻辑过期时间
        LocalDateTime expireTime = redisData.getExpireTime();

        //判断是否过期
        if(expireTime.isAfter(LocalDateTime.now()))
        {
            //未过期，返回商铺信息
            return shop;
        }


        //已过期，需要缓存重建
        //6.缓存重建
        //6.1 获取互斥锁
        String lockKey=LOCK_SHOP_KEY+id;
        Boolean isLock = tryLock(lockKey);
        //6.2 判断是否获取锁成功
        if(isLock)
        {
         //获取锁成功，开启独立的线程，实现缓存重建
            CACHE_REBUILD_EXECUTOR.submit(()->{
                try {
                    //重建缓存
                    this.saveShop2Redis(id,20L);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
                finally {
                    //释放锁
                    unLock(lockKey);
                }

            });


        }
        //6.3 成功，开启独立的线程，实现缓存重建
        //6.4 返回过期的商铺信息
//        Shop shop = getById(id);
//
//
//        stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(shop),CACHE_SHOP_TTL,TimeUnit.MINUTES);


        //结束返回
        return shop;
    }







    public Shop queryWithMutex(Long id) {

        //从Redis中查询商铺缓存
        String key=CACHE_SHOP_KEY+id;
        String shopJson = stringRedisTemplate.opsForValue().get(key);

        //判断是否存在,对与空串，null等都是false
        if(StrUtil.isNotBlank(shopJson))
        {
            //存在，从Redis中获取并返回,将Json形式转换为Sting类型
            Shop shop = JSONUtil.toBean(shopJson, Shop.class);
            return shop;
        }


        //缓存中是空串
        if(shopJson!=null)
        {
            return null;
        }


        //4.实现缓存重建
        //4.1 获取互斥锁
        String lockKey=LOCK_SHOP_KEY+id;

        Shop shop = null;
        try {
            Boolean isLock = tryLock(key);
            if(!isLock)
            {
                // 失败，休眠并重试
                Thread.sleep(50);
                queryWithMutex(id);

            }


            //成功，在根据id从数据库查询商铺
            shop = getById(id);
            //模拟重建延时
            Thread.sleep(200);

            //不存在返回错误信息
            if(shop==null)
            {
                //向Redis存入null防止缓存穿透，大量请求对数据库造成压力
                stringRedisTemplate.opsForValue().set(key,"",CACHE_NULL_TTL,TimeUnit.MINUTES);

                return null;

            }

            //存在写入redis,将bean对象转为Json存入Redis
            String jsonStr = JSONUtil.toJsonStr(shop);
            stringRedisTemplate.opsForValue().set(key,jsonStr,CACHE_SHOP_TTL, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            //释放锁
            unLock(lockKey);

        }


        //结束返回
        return shop;
    }





    public Shop queryWithPassThrough(Long id) {

        //从Redis中查询商铺缓存
        String key=CACHE_SHOP_KEY+id;
        String shopJson = stringRedisTemplate.opsForValue().get(key);

        //判断是否存在,对与空串，null等都是false
        if(StrUtil.isNotBlank(shopJson))
        {
            //存在，从Redis中获取并返回,将Json形式转换为Sting类型
            Shop shop = JSONUtil.toBean(shopJson, Shop.class);
            return shop;
        }


        //缓存中是空串
        if(shopJson!=null)
        {
            return null;
        }


        //不存在根据id从数据库查询商铺
        Shop shop = getById(id);

        //不存在返回错误信息
        if(shop==null)
        {
            //向Redis存入null防止缓存穿透，大量请求对数据库造成压力
            stringRedisTemplate.opsForValue().set(key,"",CACHE_NULL_TTL,TimeUnit.MINUTES);

            return null;

        }

        //存在写入redis,将bean对象转为Json存入Redis
        String jsonStr = JSONUtil.toJsonStr(shop);
        stringRedisTemplate.opsForValue().set(key,jsonStr,CACHE_SHOP_TTL, TimeUnit.MINUTES);
        //结束返回

        return shop;
    }



    //定义锁
    private Boolean tryLock(String key)
    {
        //利用Redis的setnx来生成互斥锁
        Boolean flag= stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.MINUTES);

        return BooleanUtil.isTrue(flag);

    }


    //释放锁
    private void unLock(String key)
    {
        stringRedisTemplate.delete(key);
    }

    //存储逻辑过期值
    private void saveShop2Redis(Long id,Long expireSecond) throws InterruptedException {

        //查询店铺数据
        Shop shop = getById(id);
        Thread.sleep(200);

        //封装逻辑过期时间
        RedisData redisData=new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSecond));

        //写入Redis
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY+id,JSONUtil.toJsonStr(redisData));


    }









    //更新数据库
    @Override
    public Result updateShop(Shop shop) {


        Long id=shop.getId();
        if(id==null)
        {
            return Result.fail("店铺id不能为空！");
        }


        //更新数据库
        updateById(shop);

        // 删除缓存
        String key=CACHE_SHOP_KEY+id;
        stringRedisTemplate.delete(key);


        return Result.ok();
    }
}
